package com.linx.rxlife

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import io.reactivex.MaybeSource
import io.reactivex.functions.Action
import io.reactivex.functions.Consumer
import io.reactivex.internal.functions.Functions
import io.reactivex.internal.operators.maybe.MaybeCallbackObserver

class MaybeLife<T>(
    private val maybeSource: MaybeSource<T>,
    owner: LifecycleOwner,
    atLeastState: Lifecycle.State = Lifecycle.State.STARTED
) : RxLife(owner, atLeastState) {

    private lateinit var onSuccess: Consumer<in T>
    private lateinit var onError: Consumer<in Throwable>
    private lateinit var onComplete: Action

    override fun onActive() {
        val observer = MaybeCallbackObserver(
            onSuccess,
            onError,
            onComplete
        )
        maybeSource.subscribe(observer)
        disposable = observer
    }

    fun observe(
        onSuccess: Consumer<in T>,
        onError: Consumer<in Throwable> = Functions.ON_ERROR_MISSING,
        onComplete: Action = Functions.EMPTY_ACTION
    ) {
        if (owner.lifecycle.currentState != Lifecycle.State.DESTROYED) {
            this.onSuccess = onSuccess
            this.onError = onError
            this.onComplete = onComplete
        }
    }

}